package com.mflex.WHSmartWhouseAd.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;

import androidx.appcompat.app.AlertDialog;

import com.mflex.WHSmartWhouseAd.model.CommonRequest;
import com.mflex.WHSmartWhouseAd.model.DelisPlateInfoModel;
import com.mflex.WHSmartWhouseAd.model.MPARTTYPE;
import com.mflex.WHSmartWhouseAd.model.OutCheckPackageInVEHNODto;
import com.mflex.WHSmartWhouseAd.utils.XToastUtils;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xutil.common.StringUtils;
import com.mflex.WHSmartWhouseAd.R;
import com.mflex.WHSmartWhouseAd.adapter.PlateInBoxAdapter;
import com.mflex.WHSmartWhouseAd.model.CommitDSPlateInBoxModel;
import com.mflex.WHSmartWhouseAd.model.WHMBarcodeInfor;
//import com.mflex.WHSmartWhouseAd.model.WHMPdaResult;
import com.mflex.WHSmartWhouseAd.utils.HideKeyBoardUtil;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xutil.net.JsonUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

//import butterknife.BindView;
//import butterknife.ButterKnife;


public class DSPlateInBoxActivity extends BaseActivity implements AdapterView.OnItemClickListener {
    // 盘标签
    EditText stvPlateBarcode;
    // 载具
    EditText stvVehicle;
    // 箱标签
    EditText stvBoxNumber;
    // 操作人员
    EditText stvOperator;

    // 扫描数量
    EditText stvActualScanNumber;
    // Datacode
//    @BindView(R.id.stv_Datacode)
    EditText stvBoxQty;
    // 已扫盘数
    EditText stvActualScanPlateNumber;
    // 批次号
    EditText stvProductCode;
    // 列表
    ListView lvList;
    // 清空
    Button buttonClear;
    Spinner stvBoxtype;
    // 提交
//    @BindView(R.id.button_submit)
//    Button buttonSubmit;

    // loading
    MiniLoadingDialog miniLoadingDialog;
    List<WHMBarcodeInfor> WHMBarcodeModelList = new ArrayList<>();
    CommitDSPlateInBoxModel model = new CommitDSPlateInBoxModel();
    WHMBarcodeInfor entity = new WHMBarcodeInfor();
    private String userName;
    private double ActualScanNumber = 0;
    private double ActualScanPlateNumber = 0;

    private String cookie = "remember_user=true; username=mmsadmin; password=bWZsZXgxMjM%3D; MMS_login_error=overdue; .AspNetCore.Antiforgery.4p8BS8WpxEI=CfDJ8IywM-4bnnxBliAj-djWgBtXSXnsLGbTtoVoYOWwvyrM8z_z17LjtH2W-K6nCSKK_Rxh7nS4WRTNO_XOQ29iU4tDHE3XsjDnjD4S2YGm8CXfgEi1f28dETYkCDpC1fD148HesAxhmB8_1dHkG8nEfkw; layuiminimenu_list=%7B%22/SmartFunction/FROZEN/Index%22%3A%22%u51BB%u7ED3%22%2C%22/SystemSecurity/Log/Index%22%3A%22%u64CD%u4F5C%u65E5%u5FD7%22%2C%22/SystemSecurity/FilterIP/Index%22%3A%22%u8BBF%u95EE%u63A7%u5236%22%2C%22/SystemSecurity/ServerMonitoring/Index%22%3A%22%u670D%u52A1%u5668%u76D1%u63A7%22%2C%22/SystemSecurity/AppLog/Index%22%3A%22%u7CFB%u7EDF%u65E5%u5FD7%22%7D; .AspNetCore.Antiforgery.BT7BH9YJexE=CfDJ8EQ4rpVl-bBAkQQmyqfstcatVsJkMPwHA7_5FArQcKksyV9afzLUFB4yE_vtj1W_gSdx16Y7T5LcClFETa4p0iLEkdIT83O5o_Ypi4DVx45k7DuLGojc_WhX6mCQ0VmqKJPKwCgrU5OwcONK16ohSNo; MMS_Mark=73a7a00e-8bad-4f90-b49b-c39f424599ed; MMS_Token=65532c31-bc9f-469f-94ce-4a8d0d3bbc0b; pc_Token=08dcffd3-086a-44cd-8a79-c2f065789a8e;";

    OutCheckPackageInVEHNODto OutCheckPackageInVEHNODtolist;
    List<MPARTTYPE> JDELOCATIONS;
    private String Jdelocation;
    private String BP;
    private String OLDBOX;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_ds_plate_in_box);
//        ButterKnife.bind(this);
        // 弹窗提示
        miniLoadingDialog = WidgetUtils.getMiniLoadingDialog(this, "加载...");
        //        id绑定
        stvOperator = findViewById(R.id.stv_Operator);
        stvPlateBarcode = findViewById(R.id.stv_PlateBarcode);
        stvVehicle = findViewById(R.id.stv_Vehicle);
        stvBoxNumber = findViewById(R.id.stv_BoxNumber);
        stvActualScanNumber = findViewById(R.id.stv_ActualScanNumber);
        stvActualScanPlateNumber = findViewById(R.id.stv_ActualScanPlateNumber);
        stvProductCode = findViewById(R.id.stv_ProductCode);
        lvList = findViewById(R.id.lvList);
        buttonClear = findViewById(R.id.button_clear);

        stvBoxQty = findViewById(R.id.stv_BoxQty);

        stvBoxtype = findViewById(R.id.stv_Boxtype);
        stvBoxNumber.setOnKeyListener(this);
        stvBoxtype.setOnKeyListener(this);
        // 传递数据
        Intent intent = getIntent();
        userName = intent.getStringExtra("userName");

        // 视图按键监听器
        stvOperator.setOnKeyListener(this);
        stvPlateBarcode.setOnKeyListener(this);
//      buttonSubmit.setOnClickListener(this);
        buttonClear.setOnClickListener(this);
        stvActualScanNumber.setText(String.valueOf(ActualScanNumber));
        stvActualScanPlateNumber.setText(String.valueOf(ActualScanPlateNumber));
        stvVehicle.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    chekVehicle();
                }
                return false;
            }
        });
        stvOperator.setFocusable(true);
        stvOperator.setFocusableInTouchMode(true);
        stvOperator.requestFocus();


//        stvBoxtype.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                floorValue = parent.getItemAtPosition(position).toString();
//            }
//            @Override
//            public void onNothingSelected(AdapterView<?> parent) {
//
//            }
//        });

//        隐藏软键盘
        HideKeyBoardUtil.disableShowSoftInput(stvOperator);
        stvOperator.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean b) {
                if (b) {
                    HideKeyBoardUtil.hideKeyBoard(DSPlateInBoxActivity.this);
                }

            }
        });
        // 点击是否删除某行
        lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                Base_Theme_AppCompat_Dialog
//                Base_Theme_AppCompat_Dialog_Alert
//                Theme_AppCompat_Dialog_MinWidth

                MediaPlayer mp = MediaPlayer.create(DSPlateInBoxActivity.this, R.raw.error_voice);
                mp.start();
                new MaterialDialog.Builder(DSPlateInBoxActivity.this)
                        .iconRes(R.drawable.icon_warning)
                        .title(R.string.tip_warning)
                        .content("操作人未输入")
                        .positiveText(R.string.lab_submit)
                        .show();


                AlertDialog.Builder builder1 = new AlertDialog.Builder(DSPlateInBoxActivity.this);
                builder1.setMessage("确定要删除当前条数据吗？")
                        .setCancelable(false)
                        .setTitle("盘号：" + WHMBarcodeModelList.get(position).getLotID())
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                delRow(WHMBarcodeModelList.get(position), position);
                                dialog.cancel();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // 用户点击了“取消”按钮
                                dialog.cancel();
                            }
                        });
                AlertDialog alert1 = builder1.create();
                alert1.show();
            }
        });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_clear:
                WHMBarcodeModelList.clear();
                PlateInBoxAdapter PlateInBoxAdapter = new PlateInBoxAdapter(DSPlateInBoxActivity.this, WHMBarcodeModelList);
                lvList.setAdapter(PlateInBoxAdapter);
                stvPlateBarcode.setText("");
//                stvVehicle.setText("");
//                stvDatacode.setText("");
                stvProductCode.setText("");
                stvBoxNumber.setText("");
                ActualScanNumber = 0;
                ActualScanPlateNumber = 0;
                stvActualScanNumber.setText(String.valueOf(ActualScanNumber));
                stvActualScanPlateNumber.setText(String.valueOf(ActualScanPlateNumber));
                String[] arr = null;
                WidgetUtils.initSpinnerStyle(stvBoxtype, arr);
                stvBoxtype.setSelection(0);
                stvBoxQty.setText("");
                stvBoxNumber.requestFocus();
                break;
//            case R.id.button_submit:
//
//                saveButtonMd(view);
//                break;
            default:
                break;
        }

    }

    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && (i == 66 || i == 61)) {
            switch (view.getId()) {
                case R.id.stv_Operator:
                    chekOperator();
                    break;
                case R.id.stv_PlateBarcode:
                    chekPlate();
                    break;
                case R.id.stv_Vehicle:
                    chekVehicle();
                    break;
                case R.id.stv_BoxNumber:
                    BoxLabel();
                    break;
                default:
                    break;
            }
        }
        return false;
    }

    // 箱标签回车事件触发接口
    private void BoxLabel() {
        if (StringUtils.isEmpty(stvVehicle.getText().toString())) {
            return;
        }
        if (StringUtils.isEmpty(stvOperator.getText().toString())) {
            return;
        }
        if (StringUtils.isEmpty(stvBoxNumber.getText().toString())) {
            return;
        }

        miniLoadingDialog.show();
        XHttp.get("api/WHSmartWhousePDA/CheckBoxInfo")
                .params("BOXNO", stvBoxNumber.getText().toString())
                .params("VEHNO", stvVehicle.getText().toString())
                .params("OLDBOX", OLDBOX)
                .syncRequest(false)
                .onMainThread(true)
                .execute(new SimpleCallBack<OutCheckPackageInVEHNODto>() {
                    @Override
                    public void onSuccess(OutCheckPackageInVEHNODto response) {

                        miniLoadingDialog.dismiss();
                        OLDBOX = "";
                        OLDBOX = stvBoxNumber.getText().toString();


                        OutCheckPackageInVEHNODtolist = response;
                        JDELOCATIONS = response.getJDELOCATIONS();
                        List<String> list = null;
                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                            list = JDELOCATIONS.stream()
                                    .map(MPARTTYPE::getTYPE).collect(Collectors.toList());
                        }

                        String[] arr = list.toArray(new String[0]);
                        WidgetUtils.initSpinnerStyle(stvBoxtype, arr);
                        stvBoxtype.setSelection(0);
                        stvBoxQty.setText(response.getBOXCOUNTQTY().toString().trim());
                        if (StringUtils.isEmpty(stvProductCode.getText().toString())) {
                            stvProductCode.setText(response.getERPLOT().toString().trim());
                        }

                    }

                    @Override
                    public void onError(ApiException e) {
                        stvBoxNumber.setText("");
                        stvBoxNumber.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                stvBoxNumber.requestFocus();
                            }
                        }, 200);
                        miniLoadingDialog.dismiss();
                        new MaterialDialog.Builder(DSPlateInBoxActivity.this)
                                .iconRes(R.drawable.icon_warning)
                                .title(R.string.tip_warning)
                                .content(e.getMessage())
                                .positiveText(R.string.lab_submit)
                                .show();
                    }
                });
    }

    // 载具回车事件触发接口
    private void chekVehicle() {
        OLDBOX = "";
        if (StringUtils.isEmpty(stvVehicle.getText().toString())) {
            return;
        }
        if (StringUtils.isEmpty(stvOperator.getText().toString())) {
            return;
        }
        miniLoadingDialog.show();
        XHttp.get("api/WHSmartWhousePDA/CheckVehicle")
                .params("Vehicle", stvVehicle.getText().toString())
//                .headers("Cookie",this.cookie)
                .syncRequest(false)
                .onMainThread(true)
                .execute(new SimpleCallBack<Boolean>() {
                    @Override
                    public void onSuccess(Boolean response) {
                        miniLoadingDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        stvVehicle.setText("");
                        stvVehicle.requestFocus();
                        miniLoadingDialog.dismiss();
                        new MaterialDialog.Builder(DSPlateInBoxActivity.this)
                                .iconRes(R.drawable.icon_warning)
                                .title(R.string.tip_warning)
                                .content(e.getMessage())
                                .positiveText(R.string.lab_submit)
                                .show();
                    }
                });
    }

    // 盘标签回车事件触发接口
    private void chekPlate() {
        if (StringUtils.isEmpty(stvPlateBarcode.getText().toString())) {
            MediaPlayer mp = MediaPlayer.create(DSPlateInBoxActivity.this, R.raw.error_voice);
            mp.start();
            new MaterialDialog.Builder(DSPlateInBoxActivity.this)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("盘号未输入")
                    .positiveText(R.string.lab_submit)
                    .show();

            return;

        }
        if (StringUtils.isEmpty(stvOperator.getText().toString())) {
            MediaPlayer mp = MediaPlayer.create(DSPlateInBoxActivity.this, R.raw.error_voice);
            mp.start();
            new MaterialDialog.Builder(DSPlateInBoxActivity.this)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("操作人未输入")
                    .positiveText(R.string.lab_submit)
                    .show();

            return;

        }
        if (StringUtils.isEmpty(stvVehicle.getText().toString())) {
            MediaPlayer mp = MediaPlayer.create(DSPlateInBoxActivity.this, R.raw.error_voice);
            mp.start();
            new MaterialDialog.Builder(DSPlateInBoxActivity.this)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("载具未输入")
                    .positiveText(R.string.lab_submit)
                    .show();
            return;
        }


        if (!StringUtils.isEmpty(stvBoxtype.getSelectedItem().toString())) {
            //List<MPARTTYPE> JDELOCATIONS;
            Jdelocation = null;
            BP = null;
            for (MPARTTYPE JDELOCATION : JDELOCATIONS) {
                if (StringUtils.equals(JDELOCATION.getTYPE(), stvBoxtype.getSelectedItem().toString())) {
                    Jdelocation = JDELOCATION.getJDELOCATION();
                    BP = JDELOCATION.getBP();
                }

            }
        }


        miniLoadingDialog.show();


        XHttp.get("api/WHSmartWhousePDA/CheckLabelInfor")
                .params("strBarcode", stvPlateBarcode.getText().toString())
                .params("Vehicle", stvVehicle.getText().toString())
                .params("BoxCode", stvBoxNumber.getText().toString())
                .params("JDELOCATION", Jdelocation)
                .params("BP", BP)
                .params("MTYPE", stvBoxtype.getSelectedItem().toString())
                .syncRequest(false)
                .onMainThread(true)
                .execute(new SimpleCallBack<WHMBarcodeInfor>() {
                    @Override
                    public void onSuccess(WHMBarcodeInfor response) {
                        miniLoadingDialog.dismiss();
                        if (response.getCustomerPn() == null) {
                            MediaPlayer mp = MediaPlayer.create(DSPlateInBoxActivity.this, R.raw.error_voice);
                            mp.start();
                            new MaterialDialog.Builder(DSPlateInBoxActivity.this)
                                    .iconRes(R.drawable.icon_warning)
                                    .title(R.string.tip_warning)
                                    .content("API接口CheckLabelInfor_New：返回空值")
                                    .positiveText(R.string.lab_submit)
                                    .show();
                            stvPlateBarcode.setText("");
                            stvPlateBarcode.requestFocus();
                            return;
                        }
                        if (WHMBarcodeModelList.size() != 0) {
                            if (!StringUtils.equals(response.getCustomerPn(), WHMBarcodeModelList.get(0).getCustomerPn())) {
                                MediaPlayer mp = MediaPlayer.create(DSPlateInBoxActivity.this, R.raw.error_voice);
                                mp.start();
                                new MaterialDialog.Builder(DSPlateInBoxActivity.this)
                                        .iconRes(R.drawable.icon_warning)
                                        .title(R.string.tip_warning)
                                        .content("扫描盘料号和第一盘料号不一致")
                                        .positiveText(R.string.lab_submit)
                                        .show();
                                stvPlateBarcode.setText("");
                                stvPlateBarcode.requestFocus();
                                return;
                            }
                        }

                        WHMBarcodeModelList.add(response);
                        PlateInBoxAdapter PlateInBoxAdapter = new PlateInBoxAdapter(DSPlateInBoxActivity.this, WHMBarcodeModelList);
                        stvBoxQty.setText(response.getCURRENTBOXQTY().toString().trim());
                        lvList.setAdapter(PlateInBoxAdapter);
                        ActualScanPlateNumber = WHMBarcodeModelList.size();
                        stvActualScanPlateNumber.setText(String.valueOf(ActualScanPlateNumber));
                        ActualScanNumber += Double.parseDouble(response.getQty());
                        stvActualScanNumber.setText(String.valueOf(ActualScanNumber));
                        stvPlateBarcode.setText("");
                        stvPlateBarcode.requestFocus();
                    }

                    @Override
                    public void onError(ApiException e) {
                        stvPlateBarcode.setText("");
                        stvPlateBarcode.requestFocus();
                        miniLoadingDialog.dismiss();
                        MediaPlayer mp = MediaPlayer.create(DSPlateInBoxActivity.this, R.raw.error_voice);
                        mp.start();
                        new MaterialDialog.Builder(DSPlateInBoxActivity.this)
                                .iconRes(R.drawable.icon_warning)
                                .title(R.string.tip_warning)
                                .content(e.getMessage())
                                .positiveText(R.string.lab_submit)
                                .show();
                    }
                });
    }

    //    操作人回车事件触发接口
    private void chekOperator() {
        if (StringUtils.isEmpty(stvOperator.getText().toString())) {
            return;
        }
        miniLoadingDialog.show();
        XHttp.get("api/WHSmartWhousePDA/CheckActionUser")
                .params("UserName", stvOperator.getText().toString())
//                .headers("Cookie",this.cookie)
                .syncRequest(false)
                .onMainThread(true)
                .execute(new SimpleCallBack<Boolean>() {
                    @Override
                    public void onSuccess(Boolean response) {
                        miniLoadingDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        stvOperator.setText("");
                        stvOperator.requestFocus();
                        miniLoadingDialog.dismiss();
                        new MaterialDialog.Builder(DSPlateInBoxActivity.this)
                                .iconRes(R.drawable.icon_warning)
                                .title(R.string.tip_warning)
                                .content(e.getMessage())
                                .positiveText(R.string.lab_submit)
                                .show();
                    }

                });

    }

    //    删除某一行
    private void delRow(WHMBarcodeInfor row, int index) {
        entity.setCustomerPo(row.getCustomerPo());
        entity.setLinenum(row.getLinenum());
        entity.setCustomerPn(row.getCustomerPn());
        entity.setQty(row.getQty());
        entity.setManuInfor(row.getManuInfor());
        entity.setMPN(row.getMPN());
        entity.setLotID(row.getLotID());
        entity.setDateCode(row.getDateCode());
        entity.setVendorCode(row.getVendorCode());
        entity.setExpDate(row.getExpDate());
        entity.setERPLot(row.getERPLot());
        entity.setADHLOT(row.getADHLOT());
        entity.setScanBarcode(row.getScanBarcode());
        entity.setBoxNo(row.getBoxNo());
        model.setVehicle(stvVehicle.getText().toString());
        model.setWHMBarcodeInfor(entity);
        String json = JsonUtil.toJson(model);
        Log.d("1234", json);
        miniLoadingDialog.show();
        XHttp.post("api/WHSmartWhousePDA/CloseLink")
                .upJson(JsonUtil.toJson(model))
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(120000)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onSuccess(String response) {
                        miniLoadingDialog.dismiss();
                        XToastUtils.success("删除成功", 3000);
                        ActualScanNumber -= Double.parseDouble(row.getQty());
                        stvActualScanNumber.setText(String.valueOf(ActualScanNumber));
                        WHMBarcodeModelList.remove(index);
                        ActualScanPlateNumber = WHMBarcodeModelList.size();
                        stvActualScanPlateNumber.setText(String.valueOf(ActualScanPlateNumber));

                        PlateInBoxAdapter PlateInBoxAdapter = new PlateInBoxAdapter(DSPlateInBoxActivity.this, WHMBarcodeModelList);
                        lvList.setAdapter(PlateInBoxAdapter);
                    }

                    @Override
                    public void onError(ApiException e) {
                        miniLoadingDialog.dismiss();
                        MediaPlayer mp = MediaPlayer.create(DSPlateInBoxActivity.this, R.raw.error_voice);
                        mp.start();
                        new MaterialDialog.Builder(DSPlateInBoxActivity.this)
                                .iconRes(R.drawable.icon_warning)
                                .title(R.string.tip_warning)
                                .content(e.getMessage())
                                .positiveText(R.string.lab_submit)
                                .show();
                    }
                });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }
}